package mi.web;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import mi.common.validator.JsonResult;
import mi.dto.BaseDTO;
import mi.enumtype.Status;
import mi.model.BaseModel;
import mi.service.IBaseService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;

/**
 * @ProjectName: [ maven 自动化集成测试系统 ]
 * @Author: [ huanghuanlai ]
 * @CreateTime: [ 2015年5月25日 下午7:24:43 ]
 * @Copy: [ dounine.com ]
 * @Version: [ V1.0 ]
 * @Description: [ 基础Action实现类 ]
 */
public abstract class BaseActionImpl<Model extends BaseModel,DTO extends BaseDTO> implements IBaseAction<Model,DTO> {
	
	@Autowired
	protected IBaseService<Model,DTO> baseService;

	@Override
	/**
	 * 修改操作,如果Entity写了Valid验证,则AOP会先拦截下来进行统一验证
	 */
	public Object edit(Model model,BindingResult result) {
		baseService.edit(model);
		return new JsonResult();
	}

	@Override
	public Model find(DTO dto) {
		return baseService.findByDTO(dto);
	}

	@Override
	public Object delete(Model model,BindingResult result) {
		baseService.delete(model);
		return new JsonResult();
	}

	@Override
	public Object add(Model model,BindingResult result) {
		baseService.insert(model);
		if(null!=model.getId()&&model.getId()>0){
			return new JsonResult();
		}
		return new JsonResult(false,FAILURE);
	}

	@Override
	public Object congeal(Model model,BindingResult result) {
		model = baseService.find(model);
		model.setStatus(Status.CONGEAL);
		baseService.edit(model);
		return new JsonResult();
	}

	@Override
	public Object thaw(Model model,BindingResult result) {
		model = baseService.find(model);
		model.setStatus(Status.THAW);
		baseService.edit(model);
		return new JsonResult();
	}
	
	@Override
	public Long getRecordCount(DTO dto){
		return baseService.count(dto);
	}

	@Override
	public Collection<Model> all(DTO dto) {
		dto.setRecordCount(getRecordCount(dto).intValue());
		return baseService.selectByPageable(dto);
	}
	
	@Override
	public Map<String, Object> maps(final DTO dto){
		return new HashMap<String, Object>(){
			private static final long serialVersionUID = 6768375339344345248L;
		{
			put("total", baseService.count(dto));
			put("rows", baseService.selectByPageable(dto));
		}};
	}
}
